<template>
	<view class="page-create uni-padding-wrap">
		<form @submit="publish">
			<view>
				<view class="row type" v-if="options.action == 'create_topic'">
					<view class="left">
						<text class="left text-muted">版块</text>
					</view>
					<view class="right">
						<picker mode="selector" @change="changeForum" :value="forumIndex" :range="forums" range-key="name">
							<view class="uni-input"><text>{{ (forums[forumIndex] && forums[forumIndex]['name']) || '' }}</text></view>
						</picker>
						<view class="">
							<icon class="iconfont icon-right" />
						</view>
					</view>
				</view>
				<view class="row type" v-if="options.action == 'create_topic'">
					<view class="left">
						<text class="left text-muted">类型</text>
					</view>
					<view class="right">
						<picker mode="selector" @change="changeType" :value="typeIndex" :range="topicTypes" range-key="text">
							<view class="uni-input"><text>{{(topicTypes[typeIndex] && topicTypes[typeIndex]['text']) || ''}}</text></view>
						</picker>
						<view class="">
							<icon class="iconfont icon-right" />
						</view>
					</view>
				</view>
				<view class="row title" v-if="options.action == 'create_topic' && type == normalType">
					<input placeholder="标题" class="input" focus="true" name="title" />
				</view>
			</view>
			
			<view class="type-report-wrap" v-if="type == reportType">
				<view class="part-header">
					<text>出击时间</text>
				</view>
				<view class="row">
					<view class="left">
						<text class="left text-muted">日期</text>
					</view>
					<view class="right">
						<picker mode="date" :value="actionDate" @change="changeActionDate" :start="startDate" :end="endDate">
								<view class="uni-input"><text>{{ actionDate }}</text></view>
						</picker>
						<view class="">
							<icon class="iconfont icon-right" />
						</view>
					</view>
				</view>
				<view class="row">
					<view class="left">
						<text class="left text-muted">时间</text>
					</view>
					<view class="right">
						<picker mode="time" :value="actionTime" @change="changeActionTime">
								<view class="uni-input"><text>{{ actionTime }}</text></view>
						</picker>
						<view class="">
							<icon class="iconfont icon-right" />
						</view>
					</view>
				</view>
				
				<view class="part-header">
					<text>出击地点</text>
				</view>
				<view class="row type">
					<view class="left">
						<text class="left text-muted">省-市-区</text>
					</view>
					<view class="right">
						<picker mode="multiSelector" 
						@columnchange="changeProvinceCityDistrict" 
						:value="provinceCityDistrictIndex" 
						:range="provinceCityDistrictData" 
						range-key="name"
						>
							<view class="uni-input">{{areaStr}}</view>
						</picker>
						<view class="">
							<icon class="iconfont icon-right" />
						</view>
					</view>
				</view>
				<view class="row action-location" >
					<textarea placeholder="详细地址" auto-height="true" name="action_location" />
				</view>
				
				<view class="part-header">
					<text>服务标签</text>
				</view>
				<view class="tags">
					<checkbox-group @change="changeTags">
						<label v-for="tag in allTags" :key="tag.id">
								<checkbox :value="tag.id" />{{tag.name}}
						</label>
					</checkbox-group>
				</view>
			</view>
			
			<view class="part-header">
				<text>正文内容</text>
			</view>
			<TextImageEditor :propsTextImageArr.sync="contentDetailTextImageArr" :type="'detail'" :propsPlaceholder="'写点什么吧...'" v-on:updateTextImage="updateTextImage"></TextImageEditor>
			
			<view v-if="options.action == 'create_topic'">
				<view class="part-header">
					<text>隐藏内容</text>
				</view>
				<view>
					<radio-group @change="hasHideRadioChange">
						<label class="radio"><radio value="0" checked="true" />无</label>
						<label class="radio"><radio value="1" />有</label>
					</radio-group>
				</view>
			</view>
			
			<view v-if="hasHide == 1">
				
				<TextImageEditor :propsTextImageArr="contentHideTextImageArr" :type="'hide'" :propsPlaceholder="contentHidePlaceholder"></TextImageEditor>
				
				<view class="row require-reply">
					<view class="uni-title">回复可见？</view>
					<view>
						<radio-group @change="requireReplyRadioChange">
							<label class="radio"><radio value="0" checked="true" />否</label>
							<label class="radio"><radio value="1" />是</label>
						</radio-group>
					</view>
				</view>
				<view class="row require-score">
					<view class="uni-title">积分门槛？</view>
					<view><input type="number" name="require_score" class="uni-input-input" maxlength="10" placeholder="不填或0表示不限制" /></view>
				</view>
			</view>
			
			<view class="submit">
				<button type="primary" class="" form-type="submit">发布</button>
			</view>
		</form>
	</view>
</template>

<script>
	import uniIcon from '@dcloudio/uni-ui/lib/uni-icon/uni-icon.vue'
	import TextImageEditor from '../../components/text-image-editor.vue'
	export default {
		data() {
			const currentDate = this.getDate()
			const currentTime = this.getCurrentTime()
			return {
				normalType: 1,
				reportType: 2,
				topicTypes: [],
				forums: [],
				typeIndex: 0,
				forumIndex: 0,
				actionDate: currentDate,
				actionTime: currentTime,
				type: "1",
				allTags: [],
				selectedTags: [],
				options: {},
				filePaths: [],
				files: [],
				uploadSucceedFileCount: 0,
				attachments: [],
				uploadServerUrl: "https://upload-z2.qiniup.com",
				maxImageCount: 6,
				autoUpload: true,
				hasHide: 0,
				requireReply: 0,
				hideAttachments: [],
				contentDetailTextImageArr: [],
				contentHideTextImageArr: [],
				contentHidePlaceholder: "写点什么吧...",
				
				areaStr: '',
				provinceCityDistrictData: [],
				provinceCityDistrictIndex: [0, 0, 0],
			}
		},
		computed: {
			startDate() {
					return this.getDate('start');
			},
			endDate() {
					return this.getDate('end');
			}
    },
		components: {
			uniIcon, TextImageEditor
		},
		async onLoad(options) {
			this.options = Object.assign({}, this.options, options)
			uni.setNavigationBarTitle({
				title: options.title
			})
			this.contentDetailTextImageArr.push({type: "text", data: {text: ""}})
			this.contentHideTextImageArr.push({type: "text", data: {text: ""}})
			if (options.action != 'create_topic') {
				return
			}
			let result = await this.$api.getTopicConfig()
			if (result.ret != 0) {
				uni.showToast({
					title: result.msg,
					icon: "null"
				})
				return
			}
			let data = result.data;
			this.topicTypes = data['topicTypes']
			this.forums = data['forums']
			this.allTags = data['tags']
			this.provinceCityDistrictData = data['provinceCityDistrict']
			if (options.fid) {
				this.forums.forEach((item, index) => {
					if (item.id == options.fid) {
						this.forumIndex = index;
					}
				})
			}
			this.updateAreaStr();
			this.updateContentHidePlaceholder()
			console.log(`this.topicTypes: `, this.topicTypes);
		},
		methods: {
			updateTextImage(type, data) {
				console.log('updateTextImage', type, data)
				if (type == 'detail') {
					this.contentDetailTextImageArr = data
				} else if (type == 'hide') {
					this.contentHideTextImageArr = data
				} else {
					throw new Error('错误的  type: ' + type)
				}
			},
			gotoSearch(e) {
				console.log(`gotoSearch`, e)
				let dataset = e.currentTarget.dataset
				let type = ""
				if (dataset.type) {
					type = dataset.type
				}
				// uni.navigateTo({
				// 	url: "../search/search?type=" + type
				// })
				uni.navigateTo({
					url: "../indexed-list/indexed-list?type=" + type
				})
			},
			changeType(e) {
				console.log(e);
				let value = e.detail.value;
				let type = this.topicTypes[value]['id']
				this.typeIndex = value
				this.type = type
				this.updateContentHidePlaceholder()
				console.log(`changeType, value: ${value}, type: ${type}`)
			},
			updateContentHidePlaceholder() {
				if (this.type == this.reportType) {
					this.contentHidePlaceholder = '有隐藏内容时，报告的时间、地点、标签也会隐藏，用户需要满足以下条件才能看到'
				} else if (this.type == this.normalType) {
					this.contentHidePlaceholder = '隐藏内容需要满足以下条件才能被用户看到'
				}
			},
			changeTags(e) {
				console.log(e)
				this.selectedTags = e.detail.value
			},
			changeForum(e) {
				console.log(e);
				let value = e.detail.value;
				this.forumIndex = value
				let forumName = this.forums[value].name
				uni.setNavigationBarTitle({
					title: `发布到${forumName}版块`
				})
				console.log(`changeForum, value: ${value}`)
			},
			changeActionDate(e) {
				this.actionDate = e.target.value
			},
			changeActionTime(e) {
				this.actionTime = e.target.value
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
						month = month - 1;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			getCurrentTime() {
				let date = new Date()
				let hour = date.getHours()
				let minute = date.getMinutes()
				hour = hour > 9 ? hour : '0' + hour
				minute = minute > 9 ? minute : '0' + minute
				return `${hour}:${minute}`
			},
			updateAttachments(attachments) {
				let ID = (new Date()).getTime();
				console.log(`${ID}, updateAttachments: `, attachments)
				this.attachments = attachments
			},
			hasHideRadioChange(e) {
				if (e.detail.value == "0") {
					this.hasHide = 0
				} else {
					this.hasHide = 1
				}
			},
			requireReplyRadioChange(e) {
				this.requireReply = e.detail.value
			},
		  updateHideAttachments(attachments) {
		  	let ID = (new Date()).getTime();
		  	console.log(`${ID}, updateHideAttachments: `, attachments)
		  	this.hideAttachments = attachments
		  },
		
		  async publish(e) { 
				let action = this.options.action;
				if (action == "create_topic") {
				  await this.publishTopic(e.detail.value);
				} else if (action == "create_comment") {
				  await this.publishComment(e.detail.value);
				} else {
				  throw new Error("invalid action: " + action);
				  return;
				}   
			},
			async publishTopic(data) {
			  let methodName = "publishTopic";
				data.fid = this.forums[this.forumIndex].id;
				data.type = this.type
				if (this.type == this.reportType) {
					data.action_date = this.actionDate
					data.action_time = this.actionTime
					//省市区
					data.action_province = this.provinceCityDistrictData[0][this.provinceCityDistrictIndex[0]]['name']
					data.action_city = this.provinceCityDistrictData[1][this.provinceCityDistrictIndex[1]]['name']
					data.action_district = this.provinceCityDistrictData[2][this.provinceCityDistrictIndex[2]]['name']
					//标签
					data.tags = this.selectedTags
				}
				//详情部分
				data.content_detail = this.contentDetailTextImageArr
				//隐藏部分
				if (this.hasHide == 1) {
					data.has_hide = 1
					data.require_reply = this.requireReply
					data.content_hide = this.contentHideTextImageArr
				} else {
					data.has_hide = 0
				}
				
				console.log(`${methodName},topicTypes data: `, data);
				
				// return
			  let res = await this.$api.createTopic(data);
			  console.log(`${methodName}, res: `, res);
			  if (res.ret === 0) {
					this.$store.commit('setNewTopic', res.data.data[0])
					uni.navigateBack()
			  }
			},

			async publishComment(data) {
			  let methodName = "publishComment";
				data.tid = this.options.tid
			  data.content_detail = this.contentDetailTextImageArr;
				console.log(`${methodName}, data: `, data);
			  let res = await this.$api.createComment(data);
			  console.log(`${methodName}, res: `, res);
			  
			  if (res.ret === 0) {
					this.$store.commit('setNewComment', res.data.data[0])
					uni.navigateBack()
			  }
			},
			async changeProvinceCityDistrict(e) {
				console.log(e)
				let detail = e.detail
				let column = detail.column
				let value = detail.value
				let columnCount = this.provinceCityDistrictIndex.length;
				//自已列，修改索引
				this.provinceCityDistrictIndex.splice(column, 1, value)
				if (column < columnCount - 1) {
					for (var i = column + 1; i <= columnCount - 1; i++) {
						let dataIndex = 0
						if (i - column == 1) {
							 dataIndex = value
						}
						let pid = this.provinceCityDistrictData[i - 1][dataIndex].id
						console.log('handle column: ' + i + ', dataIndex: ' + dataIndex + ', pid: ' + pid)
						var result = await this.$api.listArea({"__resource_id": pid})
						this.provinceCityDistrictData.splice(i, 1, result.data)
						this.provinceCityDistrictIndex.splice(i, 1, 0)
					}
				}
				this.updateAreaStr();
			},
			updateAreaStr() {
				let province = this.provinceCityDistrictData[0][this.provinceCityDistrictIndex[0]]['name'] || '-'
				let city = this.provinceCityDistrictData[1][this.provinceCityDistrictIndex[1]]['name'] || '-'
				let district = this.provinceCityDistrictData[2][this.provinceCityDistrictIndex[2]]['name'] || '-'
				this.areaStr = province + "-" + city + "-" + district
				console.log('updateAreaStr', this.areaStr)
			}
		},
		events: {
			
		},
		onShow() {
			console.log('page/create onShow')
		}
	}
</script>

<style lang="scss">
.page-create {
	.part-header {
		margin-top: 20upx;
		font-size: 36upx;
		font-weight: bold;
	}
  .row {
		border-bottom: 1px solid #eee;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		.right {
			display: flex;
			align-items: center;
			.icon-right {
				margin-left: 10rpx;
			}
		}
		.textarea {
			min-height: 100upx;
			width: 100%;
		}
    .input {
      width: 100%;
    }
		
  }
	.title {
		.input {
			font-size: 40upx;
			padding: 10upx 0;
		}
	}
  .content {
    .textarea {
      min-height: 300upx;
      width: 100%;
    }
  }
	.action-location {
		padding: 30upx 0;
	  .textarea {
	    min-height: 100upx;
	    width: 100%;
	  }
	}
  .images {
    margin-bottom: 20upx;
  }
	.type {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
	}
	.submit {
		padding: 100upx 0;
	}
	.text-muted {
		color: #666;
	}
	.hide {
		margin-top: 20upx;
	}
	.require-score {
		input {
			text-align: right;
		}
	}
	.tags {
		margin-top: 20upx;
		checkbox {
			transform:scale(0.7)
		}
	}
}
</style>
